<?php

//计算地址经纬度
function reckon($dz) {

    $word = urldecode($dz);

    $file = @file_get_contents('http://api.map.baidu.com/geocoder/v2/?address=' . $dz . '&output=json&ak=nmiLUepTcrdLe6u0uHIYzD1f');


    $json = json_decode($file, true);
    $json = $json[result][location];


    $Location[] = $json[lng];
    $Location[] = $json[lat];
    return $Location;
}

//获取毫秒
function millisecond() {
    $time = explode(" ", microtime());
    $time = $time [1] . ($time [0] * 1000);
    $time2 = explode(".", $time);
    $time = $time2 [0];
    return $time;
}

function time2string($second) {
    $day = floor($second / (3600 * 24));
    $second = $second % (3600 * 24); //除去整天之后剩余的时间
    $hour = floor($second / 3600);
    $second = $second % 3600; //除去整小时之后剩余的时间 
    $minute = floor($second / 60);
    $second = $second % 60; //除去整分钟之后剩余的时间 
    //返回字符串
    if ($hour > 0)
	$day = $day + 1;
    else
	$day = $day;
    return $day;
}

function time3string($second, $time) {
    $day = floor($second / (3600 * 24));
    $second = $second % (3600 * 24); //除去整天之后剩余的时间
    $hour = floor($second / 3600);
    $second = $second % 3600; //除去整小时之后剩余的时间
    $minute = floor($second / 60);
    $second = $second % 60; //除去整分钟之后剩余的时间
    //返回字符串
    //return $day.'天'.$hour.'小时'.$minute.'分'.$second.'秒';
    $shijian = date("H:i", $time);
    $riqi = date("m月d日 H:i", $time);
    if ($day < 1) {
	$t = (int) date('H', time());
	if ((int) $hour - $t <= 0) {
	    return "今天" . $shijian;
	} else
	    return $riqi;
    }
    else {
	return $riqi;
    }
}

function time4string($second) {
    $day = floor($second / (3600 * 24));
    $second = $second % (3600 * 24); //除去整天之后剩余的时间
    $hour = floor($second / 3600);
    $second = $second % 3600; //除去整小时之后剩余的时间
    $minute = floor($second / 60);
    $second = $second % 60; //除去整分钟之后剩余的时间
    //返回字符串
    //return $day.'天'.$hour.'小时'.$minute.'分'.$second.'秒';

    if ($day < 1) {
	if ($hour > 1)
	    return $hour . "小时前";
	else {
	    if ($minute > 1)
		return $minute . "分钟前";
	}
    }
    else {
	return $day . "天前";
    }
}

function monthc($yue = 0) {
    return mktime(0, 0, 0, $yue + 1, 1, date('Y'));
}

function monthe($yue = 0) {
    return mktime(23, 59, 59, $yue + 2, 0, date('Y'));
}

function var_urlencode($var) {
    if (empty($var)) {
	return false;
    }
    if (is_array($var)) {
	foreach ($var as $k => $v) {
	    if (is_scalar($v)) {//if用来处理不是数组的情况
		$var [$k] = urlencode($v);
	    } else {//else用来处理数组
		$var [$k] = var_urlencode($v);
	    }
	}
    } else {//用来处理数组
	$var = urlencode($var);
    }
    return $var;
}

function var_json_encode($var) {
    $_var = var_urlencode($var);
    $_str = json_encode($_var);
    return urldecode($_str);
}

//获取IP地址
function get_ip() {
    if (isset($_SERVER)) {
	if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
	    $IPaddress = $_SERVER["HTTP_X_FORWARDED_FOR"];
	} else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
	    $IPaddress = $_SERVER["HTTP_CLIENT_IP"];
	} else {
	    $IPaddress = $_SERVER["REMOTE_ADDR"];
	}
    } else {
	if (getenv("HTTP_X_FORWARDED_FOR")) {
	    $IPaddress = getenv("HTTP_X_FORWARDED_FOR");
	} else if (getenv("HTTP_CLIENT_IP")) {
	    $IPaddress = getenv("HTTP_CLIENT_IP");
	} else {
	    $IPaddress = getenv("REMOTE_ADDR");
	}
    }
    return $IPaddress;
}

function check_remote_file_exists($url) {
    $ch = curl_init();
    $timeout = 10;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $contents = curl_exec($ch);
    //echo $contents;
    if (preg_match("/404/", $contents)) {
	return false;
    }
    return true;
}

//多维数据排序（降序SORT_DESC，升序SORT_ASC）
function my_sort($arrays, $sort_key, $sort_order = SORT_DESC, $sort_type = SORT_NUMERIC) {
    if (is_array($arrays)) {
	foreach ($arrays as $array) {
	    if (is_array($array)) {
		$key_arrays[] = $array[$sort_key];
	    } else {
		return false;
	    }
	}
    } else {
	return false;
    }
    array_multisort($key_arrays, $sort_order, $sort_type, $arrays);
    return $arrays;
}

function juhecurl($url, $params = false, $ispost = 0) {
    $httpInfo = array();
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if ($ispost) {
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
	curl_setopt($ch, CURLOPT_URL, $url);
    } else {
	if ($params) {
	    curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
	} else {
	    curl_setopt($ch, CURLOPT_URL, $url);
	}
    }
    $response = curl_exec($ch);
    if ($response === FALSE) {
	//echo "cURL Error: " . curl_error($ch);
	return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return $response;
}

/**
 * @param $url 上传地址
 * @param array $data 上传数组
 * @return mixed|string
 */
function getcurl($url, $data = array()) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');
    curl_setopt($ch, CURLOPT_URL, $url);
    if (!empty($data)) {
	curl_setopt($ch, CURLOPT_POST, '1');
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    //禁用后cURL将终止从服务端进行验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $res = curl_exec($ch);
    if (curl_error($ch)) {
	return '错误信息:' . curl_error($ch);
    }
    curl_close($ch);
    return $res;
}

//添加操作记录
function addlog($data) {
    $logmodel = M("chat_adminlog");
    $logmodel->add($data);
}

//键值对数组（枚举）
function getenumbykey($key) {
    $arr = array();
    switch ($key) {
	case 'app_code_list':
	    $arr = C('APP_CODE_LIST');
	    break;
	case 'app_state':
	    $arr = C('APP_STATE');
	    break;
	case 'yn':
	    $arr = C('YN');
	    break;
	case 'switch':
	    $arr = C('SWITCH');
	    break;
	case 'state':
	    $arr = C('STATE');
	    break;
	case 'flag':
	    $arr = C('FLAG');
	    break;
	case 'sex':
	    $arr = C('SEX');
	    break;
	case 'success':
	    $arr = C('SUCCESS');
	    break;
	case 'admin_state':
	    $arr = C('ADMIN_STATE');
	    break;
	case 'adminlog_type':
	    $arr = C('ADMIN_LOG_TYPE');
	    break;
	case 'adminrole_level':
	    $arr = C('ADMIN_ROLE_LEVEL');
	    break;
	case 'adminrole_state':
	    $arr = C('ADMIN_ROLE_STATE');
	    break;
	case 'balancelog_state':
	    $arr = C('BALANCE_LOG_STATE');
	    break;
	case 'balancelog_type':
	    $arr = C('BALANCE_LOG_TYPE');
	    break;
	case 'balancelog_toggle':
	    $arr = C('BALANCE_LOG_TOGGLE');
	    break;
	case 'banner_state':
	    $arr = C('BANNER_STATE');
	    break;
	case 'banner_type':
	    $arr = C('BANNER_TYPE');
	    break;
	case 'gift_state':
	    $arr = C('GIFT_STATE');
	    break;
	case 'recharge_state':
	    $arr = C('RECHARGE_STATE');
	    break;
	case 'recharge_type':
	    $arr = C('RECHARGE_TYPE');
	    break;
	case 'useridentity_state':
	    $arr = C('USER_IDENTITY_STATE');
	    break;
	case 'userlogin_state':
	    $arr = C('USER_LOGIN_STATE');
	    break;
	case 'userstate_state':
	    $arr = C('USER_STATE');
	    break;
	case 'withdrawaccount_type':
	    $arr = C('WITHDRAW_ACCOUNT_TYPE');
	    break;
	case 'withdrawals_type':
	    $arr = C('WITHDRAWALS_TYPE');
	    break;
	case 'withdrawals_state':
	    $arr = C('WITHDRAWALS_STATE');
	    break;
	case 'usercalllog_state':
	    $arr = C('USER_CALL_LOG_STATE');
	    break;
	case 'usercalllog_isrecord':
	    $arr = C('USER_CALL_IS_RECORD');
	    break;
	case 'usermembernum_state':
	    $arr = C('USER_MEMBER_NUM_STATE');
	    break;
	case 'usermembernum_type':
	    $arr = C('USER_MEMBER_NUM_TYPE');
	    break;
	case 'usermembernum_level':
	    $arr = C('USER_MEMBER_NUM_LEVEL');
	    break;
	case 'usernumsection_state':
	    $arr = C('USER_NUM_SECTION_STATE');
	    break;
	case 'labor_withdrawal_status':
        $arr = C('LABOR_WITHDRAWAL_STATUS');
        break;
    case 'labor_withdrawal_returnstatus':
        $arr = C('LABOR_WITHDRAWAL_RETURNSTATUS');
        break;
    case 'labor_withdrawal_bankclass':
        $arr = C('LABOR_WITHDRAWAL_BANKCLASS');
        break;
    case 'anchor_grade_state':
        $arr = C('ANCHOR_GRADE_STATE');
        break;
	default:
	    break;
    }
    return $arr;
}

//通过键值对数组（枚举）生成下拉框数组
function getarrbyenum($enum) {
    $arr = array();
    foreach ($enum as $key => $value) {
	$item = array('value' => $key, 'text' => $value);
	array_push($arr, $item);
    }
    return $arr;
}

function checkpower() {
    $action = trim(__ACTION__, '/');
    $actions = explode('/', $action);
    $action = strtolower($actions[2]);
    $link = $action[1] . '/' . $action[2];
    if (empty($action)) {
	$action = strtolower($actions[1]);
	$link = $action[0] . '/' . $action[1];
    }
    $model = M('chat_adminrole');
    $admin_role_id = session("admin_role_id");
    $map['id'] = $admin_role_id;
    $role = $model->where($map)->find();
    if ($role) {
	$level_first_id = $role['level_first_id'];
	$level_second_id = $role['level_second_id'];
    }
}

function getuitime($time = 0, $format = 'num') {
    if ($time >= 86400) {
	$day = (int) ($time / 86400) . ($format == 'cn' ? '天' : '.');
	$time = $time % 86400;
    }
    $time = $time - 28800;
    $format = $format == 'cn' ? 'H小时i分s秒' : 'H:i:s';
    $time = $day . date($format, $time);
    return $time;
}

//function getuitime($time, $format = '%02d') {
//    $format = empty($format) ? '%02d' : $format;
//    $timestr = '';
//    $time = $time > 0 ? (int) $time : 0;
//    if ($time >= 86400) {
//	$timestr .= sprintf($format, (int) ($time / 86400)) . '天';
//	$time = $time % 86400;
//    }
//    if ($time >= 3600) {
//	$timestr .= sprintf($format, (int) ($time / 3600)) . '小时';
//	$time = $time % 3600;
//    }
//    if ($time >= 60) {
//	$timestr .= sprintf($format, (int) ($time / 60)) . '分钟';
//	$time = $time % 60;
//    }
//    if ($time >= 0) {
//	$timestr .= sprintf($format, (int) $time) . '秒';
//    }
//    $timestr = empty($timestr) ? (sprintf($format, 0) . '秒') : $timestr;
//    return $timestr;
//}

function getuitime2($time, $ctime) {
    $time = $time < 0 ? 0 : (int) $time;
    $ctime = $ctime < 0 ? 0 : (int) $ctime;
    $time = $time + $ctime;
    $time = date('Y-m-d H:i', $time);
    return $time;
}

/* * ---------------------------redis操作--------------------------------* */

function newredisoperate($selectid) {
    $host = "r-bp1f86cf38e6cad4.redis.rds.aliyuncs.com";
    $port = 6379;
    $pwd = "GCSkj0577";
    $redis = new Redis();
    $redis->connect($host, $port);
    $redis->auth($pwd);
    $redis->select($selectid);
    return $redis;
}

//添加到hash表
function newredisadd($selectid, $key, $field, $value) {
    header('Content-Type:text/html;charset=utf-8');
    $redis = newredisoperate($selectid);
    if ($redis->hSet($key, $field, $value))
	return true;
    else
	return false;
}

//获得一个哈希表中所有的 key 和 value
function newredisgetall($selectid, $key) {
    header('Content-Type:text/html;charset=utf-8');
    $redis = newredisoperate($selectid);
    return $redis->hGetAll($key);
}

//获取哈希表的某指定key下字段的value
function newredisget($selectid, $key, $field) {
    header('Content-Type:text/html;charset=utf-8');
    $redis = newredisoperate($selectid);
    return $redis->hGet($key, $field);
}

//给哈希表中某 key 增加一个整数值
function newredishIncrBy($selectid, $key, $field, $incr) {
    header('Content-Type:text/html;charset=utf-8');
    $redis = newredisoperate($selectid);
    if ($redis->hIncrBy($key, $field, $incr))
	return true;
    else
	return false;
}

//给哈希表中某 key 增加一个浮点值
function newredishfloatcrBy($selectid, $key, $field, $incr) {
    header('Content-Type:text/html;charset=utf-8');
    $redis = newredisoperate($selectid);
    if ($redis->hincrbyfloat($key, $field, $incr))
	return true;
    else
	return false;
}

//给哈希表中某 key 增加一个浮点数值
function newredishIncrByFloat($selectid, $key, $field, $incrFloat) {
    header('Content-Type:text/html;charset=utf-8');
    $redis = newredisoperate($selectid);
    if ($redis->hIncrByFloat($key, $field, $incrFloat))
	return true;
    else
	return false;
}

//删除指定key内容
function newredisdelete($selectid, $key) {
    $redis = newredisoperate($selectid);
    $redis->del($key);
}

//是否存在key
function newexists($selectid, $key) {
    $redis = newredisoperate($selectid);
    return $redis->exists($key);
}

//获取指定条件key列表
function newkeys($selectid, $tiaojian) {
    $redis = newredisoperate($selectid);
    return $redis->keys($tiaojian);
}

//设置整个哈希表
function newredishmset($selectid, $key, $value) {
    header('Content-Type:text/html;charset=utf-8');
    $redis = newredisoperate($selectid);
    return $redis->hmset($key, $value) ? true : false;
}

//添加到string表
function newredisstringadd($selectid, $key, $value) {
    header('Content-Type:text/html;charset=utf-8');
    $redis = newredisoperate($selectid);
    if ($redis->set($key, $value))
	return true;
    else
	return false;
}

//添加到string表
function newredisstringtimeadd($selectid, $key, $value, $time) {
    header('Content-Type:text/html;charset=utf-8');
    $redis = newredisoperate($selectid);
    if ($redis->set($key, $value)) {
	$redis->expire($key, $time);
	return true;
    } else
	return false;
}

//获取到string表
function newredisstringget($selectid, $key) {
    header('Content-Type:text/html;charset=utf-8');
    $redis = newredisoperate($selectid);
    return $redis->get($key);
}

//获取到列表
function newredislistget($selectid, $key, $start, $end) {
    header('Content-Type:text/html;charset=utf-8');
    $redis = newredisoperate($selectid);
    return $redis->lRange($key, $start, $end);
}

//获取到列表数量
function newredislistgetCount($selectid, $key) {
    header('Content-Type:text/html;charset=utf-8');
    $redis = newredisoperate($selectid);
    return $redis->lSize($key);
}

//添加到列表
function newredislistwAdd($selectid, $key, $value) {
    header('Content-Type:text/html;charset=utf-8');
    $redis = newredisoperate($selectid);
    return $redis->rPush($key, $value);
}

function get_user_id($code = 'mt') {
    if (empty($code)) {
	$code = get_app_code();
    }
    $user_id = "";
    $model = M('chat_usermembernum');
    $data = $model->where(['state' => '1', 'app_flag' => $code])->field('user_id')->limit(1)->order('rand()')->select();
    if ($data != null) {
	$user_id = $data[0]['user_id'];
    } else {
	$res = 0;
	user_id:
	$user_id = rand(900000000, 999999999);
	$where['user_id'] = $user_id;
	$where['state'] = array('in', '2,3');
	$where['app_flag'] = $code;
	$tx_order_id = $model->where($where)->getField('id');
	if ($tx_order_id) {
	    goto user_id;
	}
	$data['user_id'] = $user_id;
	$data['state'] = '1';
	$data['app_flag'] = $code;
	$data['ctime'] = time();
	$data['start_id'] = '900000000';
	$data['end_id'] = '999999999';
	$result = $model->add($data);
	if ($res > 5) {
	    $this->return = [
		'ret' => '1002',
		'code' => '获取会员号失败，请通知管理员'
	    ];
	    return true;
	}
	if ($result !== false) {
	    
	} else {
	    $res += 1;
	    goto user_id;
	}
    }

    return $user_id;
}

function get_app_text($code = 'md', $list = []) {
    if (!count($list)) {
	$list = getenumbykey('app_code_list');
    }
    $text = $list[$code];
    return $text;
}

function get_app_code($text = '摩登星球', $list = []) {
    if (!count($list)) {
	$list = getenumbykey('app_code_list');
    }
    $code = (string) array_search($text, $list);
    return $code;
}

function get_safety_app_code($code = 'md', $list = []) {
    if (!count($list)) {
	$list = getenumbykey('app_code_list');
    }
    $text = get_app_text($code, $list);
    if (empty($text)) {
	$code = get_app_code('摩登星球', $list);
    }
    return $code;
}

function check_app_code($code, $list = []) {
    if (!count($list)) {
	$list = getenumbykey('app_code_list');
    }
    $text = get_app_text($code, $list);
    return $text;
}
function secToTime($times){
    $result = '00时00分00秒';
    if ($times>0) {
        $hour = floor($times/3600);
        $minute = floor(($times-3600 * $hour)/60);
        $second = floor((($times-3600 * $hour) - 60 * $minute) % 60);
        if($minute==0){
            $minute='00';
        }
        if($second <= 9 ){
            $second='0'.$second;
        }
        $result = $hour.':'.$minute.':'.$second.'秒';
    }
    return $result;
}
function Turn_age($times){
    $age = date('Y', time()) - date('Y', $times)- 1;
    if (date('m', time()) == date('m', $times)){

        if (date('d', time()) > date('d', $times)){
            $age++;
        }
    }elseif (date('m', time()) > date('m', $times)){
        $age++;
    }
    return $age;
}

/**
 * @return bool
 * @desc 判断是否是超级管理员权限
 */
function checkSuperAdmin() {
    if (session('admin_id') ==1) {
        return true;
    }else{
        return false;
    }
}

?> 